package com.example.module_home.network

import android.util.Log
import androidx.lifecycle.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.IOException
import java.net.URL
import java.net.URLConnection

class CoroutineFlowViewModel : ViewModel() {

    private var _netResponseData: MutableLiveData<List<PostEntity>> = MutableLiveData()


    val netResponseData: LiveData<List<PostEntity>>
        get() = _netResponseData

    private var _album: MutableLiveData<List<AlbumEntity>> = MutableLiveData()


    val album: LiveData<List<AlbumEntity>>
        get() = _album



    fun fetchData() {

        viewModelScope.launch {
           // fetchPost()
            fetchAlbum()

        }

    }

    private suspend fun fetchPost() {
        Repository.getPost()
            .catch { e ->
                Log.e("exception", "==" + e.message)
            }
            .collectLatest {
                _netResponseData.value = it
                Log.e("fetchPost_heart_beat", "==" + it.size)
            }
    }


    private suspend fun fetchAlbum() {
        Repository.getAlbum()
            .catch { e ->
                Log.e("exception", "==" + e.message)

            }
            .collect {
                _album.value = it
            }
    }



}